<?php

/**
 * Created by PhpStorm.
 * User: chen
 * Date: 2017/2/13
 * Time: 13:17
 */
class CommAction extends Action{
    public function _initialize(){
        header("Content-Type: text/html;charset=utf-8");
        import('ORG.Util.Session');
        import('ORG.Util.Cookie');
        
        session::set('action',MODULE_NAME);
        session::set('func',ACTION_NAME);

        $this->baseCheck();
        $this->loadConfig();
        $this->loginRequireCheck(MODULE_NAME,ACTION_NAME);
        
    }
 

    public function loadConfig()
    {
        $tmplParseString = array();
        $tmplParseString['__STATIC__'] = __APP__ . '/static';
        $tmplParseString['__UPLOAD__'] = __APP__ . '/upload';
        $tmplParseString['__SITE_URL__'] = __APP__;
        C('TMPL_PARSE_STRING', $tmplParseString);
        $this->assign('baseurl', getBaseUrl());
        //分享的签名信息
        $sign = $this->getSign();
        $this->assign('sign', $sign);

    }

    public function baseInfo()
    {
        if (!APP_DEBUG) {
            if (!$this->isMobile()) {
                $this->error('仅支持移动端访问！');
            }
            if (strpos($_SERVER["HTTP_USER_AGENT"], 'MicroMessenger')) {

            } else {
                $this->error('仅支持从微信访问！');
            }
        }
    }

    /**
     * 基本检查
     */
    public function baseCheck()
    {
        //必须给出微信标示
        $openid = trim(I('get.openid'));
        if ($openid == null) {
            $openid = Session::get('openid');
        }
        
        if (empty($openid)) {

            //跳转到用户登录授权
            $this->getWxLogin();
        } else {
                $map = array();
                //$userModel = D('Wxuser');
                $map['openid'] = $openid;
                $rs = M('wxuser')->where($map)->find();
                if ($rs) {
                    Session::set('openid', $openid);    //获取到合法的openid
                } else {
                    $this->goToLogin();//先清空缓存，跳转到用户登录授权
                }

        }
    }

    /**
     * 跳转到登陆页面
     */
    public function goToLogin()
    {
        session::set('openid', null);
        $this->getWxLogin();
    }

    /**
     * 获取用户信息
     */
    public function getUser()
    {
        $user = D('Wxuser')->findByOpenId(Session::get('openid'));
        return $user;
    }


    /**
     * 跳转到微信授权登陆
     */
    public function getWxLogin()
    {
        
        redirect(U('GetInfo/index'));
    }

    /**
     * 获取分享所需要的配置信息
     */
    public function getSign(){
        import('@.ORG.Util.Jssdk');
        $appId = 'wx7a4c3c0122f36dad';
        $appSecret = '0c65c08c46b9c86871fe3d0c2aa457fb';
        $jssdk = new Jssdk($appId, $appSecret);
        $signPackage = $jssdk->GetSignPackage();
        return $signPackage;
    }

    /**
     * 判断是否是移动端访问
     * @return bool
     */
    public function isMobile()
    {
        import('@.ORG.Util.MobileDetect');
        $Detect = new Mobile_Detect();
        return $Detect->isMobile();
    }

    public function getUserId(){
        $userModel = D('Wxuser');
        // $id = $userModel->getIdByOpenId(session::get('openid'));
        $id = $userModel->where(array('openid'=>session::get('openid')))->getField('id');
        return $id;
    }
    

    public function simpleAlert($content,$url='javascript:history.go(-1);'){
        echo "<SCRIPT language=JavaScript>alert('$content');location.href='$url';</SCRIPT>";
        echo ' ';
        exit;

    }

   public function httpGet($url)
    {
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return $output;
    }

    public function getVipid(){
        do {
            $id = '8888'.rand_string(12,1);
            $rs = M('VipList')->where(array('vipid'=>$id))->find();
        } while ($rs);
        
        return $id;

    } 

    /**
     * 发送message信息
     */
    public function sendMessage($title,$content){
        $messageModel=D('Message');
        $data=array();
        $data['openid']=session::get('openid');
        $data['createtime']=time();
        $data['content']=$content;
        $data['title']=$title;
        // $data['name']=$name;
        $data['read']=0;
        $messageModel->data($data)->add();
    }

    public function savePv()
    {
        $ip = $_SERVER["REMOTE_ADDR"];
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        $params = $_SERVER['QUERY_STRING'];
        $createtime = time();
        $pvModel = D('Pv');
        $data = array();
        $data['ip'] = $ip;
        $data['url'] = $url;
        $data['params']=$params;
        $data['openid']=session::get('openid');
        $data['createtime'] = $createtime;
        $pvModel->add($data);
        $this->addPv($data);//添加到总库
    }

    //部分模块需要登录才能操作
    public function loginRequireCheck($action,$func){
        $userid = $this->getUserId();
        $data['action'] = $action;
        $data['func'] = $func;
        $exist = M('login_redirect')->where(array('w_id'=>$userid))->find();
        if($exist){
            M('login_redirect')->where(array('w_id'=>$userid))->save($data);
        }else{
            $data['w_id'] = $userid;
            M('login_redirect')->add($data);
        }
        $info = M('login_redirect')->where(array('w_id'=>$userid))->find();
        if($info['action'] == 'OfficeHolder'){
            if($info['account'] == '' || $info['pwd'] == '' || $info['createtime'] < time()){
                $this->redirect('Login/login');
            }
        }
        
    }

    public function get_token(){
        $tokenTime = M("plat")->where('id=3')->field('accessToken,accessTime')->find();
        if(time()>$tokenTime['accessTime']){
            $appId = 'wx7a4c3c0122f36dad';
            $appSecret = '513911e14d07ad3fa5f8267d5c521059';
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);
            $jsoninfo = json_decode($output, true);
            $access_token = $jsoninfo["access_token"];
            if($access_token){
                $data['accessToken']=$access_token;
                $ret=M('plat')->where("id=3")->save($data);
                if($ret){
                    return $access_token;
                }
            }else{
                return array(23,32);
            }
        }else{
            return $access_token=$tokenTime['accessToken'];
        }
    }
}